package com.osce.web.controller.system;

import com.osce.common.annotation.Log;
import com.osce.common.constant.UserConstants;
import com.osce.common.core.controller.BaseController;
import com.osce.common.core.entity.AjaxResult;
import com.osce.common.core.entity.entity.SysUser;
import com.osce.common.core.entity.vo.TeacherExcelVo;
import com.osce.common.core.page.TableDataInfo;
import com.osce.common.enums.BusinessType;
import com.osce.common.utils.SecurityUtils;
import com.osce.common.utils.StringUtils;
import com.osce.common.utils.poi.ExcelUtil;
import com.osce.interfaces.system.ISysUserService;
import com.osce.interfaces.system.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 教师信息
 *
 * @author doudou
 */
@RestController
@RequestMapping("/system/teacher")
public class TeacherController extends BaseController {

    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private ISysUserService userService;


    /**
     * 获取教师列表
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        user.setUserType(UserConstants.TEACHER_TYPE);
        startPage();
        List<SysUser> list = teacherService.selectList(user);
        return getDataTable(list);
    }

    /**
     * 新增教师
     */
    @PreAuthorize("@ss.hasPermi('system:teacher:add')")
    @Log(title = "教师管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增教师'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增教师'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增教师'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUserType(UserConstants.TEACHER_TYPE);
        user.setRoleIds(UserConstants.TEACHER_ROLES);
        return toAjax(userService.insertUser(user));
    }

    /**
     * 导出模板
     */
    @PostMapping("/importTemplate")
    @PreAuthorize("@ss.hasPermi('system:teacher:import')")
    public void importTemplate(HttpServletResponse response) {
        new ExcelUtil<>(TeacherExcelVo.class).importTemplateExcel(response, "教师数据");
    }

    @Log(title = "导出教师列表", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:teacher:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user, String exportFields, String encryptFields) {
        user.setUserType(UserConstants.TEACHER_TYPE);
        List<SysUser> list = teacherService.selectList(user);
        List<TeacherExcelVo> userList = teacherService.toExcelVo(list);
        ExcelUtil<TeacherExcelVo> util = new ExcelUtil<>(TeacherExcelVo.class);
        
        // 处理需要加密的字段
        if (StringUtils.isNotEmpty(encryptFields)) {
            String[] fieldsToEncrypt = encryptFields.split(",");
            util.encryptColumn(fieldsToEncrypt);
        }

        // 定义所有可导出的字段
        List<String> allExportableFields = new ArrayList<>();
        allExportableFields.add("userName"); // 登录账户
        allExportableFields.add("nickName"); // 教师姓名
        allExportableFields.add("email"); // 邮箱
        allExportableFields.add("identity"); // 身份证
        allExportableFields.add("phonenumber"); // 手机号码
        allExportableFields.add("birthday"); // 生日
        allExportableFields.add("sex"); // 用户性别
        allExportableFields.add("deptName"); // 所属科室
        allExportableFields.add("school"); // 学校
        allExportableFields.add("base"); // 学科
        allExportableFields.add("post"); // 职称
        // 军人表相关字段
        allExportableFields.add("nation"); // 民族
        allExportableFields.add("nativePlace"); // 籍贯
        allExportableFields.add("enlistmentTime"); // 入伍时间
        allExportableFields.add("partyJoiningTime"); // 入党时间
        allExportableFields.add("enlistmentPlace"); // 入伍地
        allExportableFields.add("educationDegreeId"); // 学历学位
        allExportableFields.add("bloodType"); // 血型
        allExportableFields.add("personnelCategoryId"); // 人员类别
        allExportableFields.add("securityCardNo"); // 保障卡号
        allExportableFields.add("militaryIdNo"); // 军人证件号
        allExportableFields.add("organizationalCategory"); // 总支
        allExportableFields.add("dutyTitle"); // 部职别
        
        // 计算需要排除的字段
        List<String> excludeFields = new ArrayList<>();
        
        if (StringUtils.isNotEmpty(exportFields)) {
            // 如果指定了导出字段，排除不在选中列表中的字段
            Set<String> selectedFields = new HashSet<>(Arrays.asList(exportFields.split(",")));
            for (String field : allExportableFields) {
                if (!selectedFields.contains(field)) {
                    excludeFields.add(field);
                }
            }
        } else {
            // 如果没有指定导出字段，默认排除学校、学科、职称三个字段
            excludeFields.add("school"); // 学校
            excludeFields.add("base"); // 学科
            excludeFields.add("post"); // 职称
        }
        
        // 调用hideColumn方法排除不需要的字段
        if (!excludeFields.isEmpty()) {
            util.hideColumn(excludeFields.toArray(new String[0]));
        }

        // 导出Excel
        util.exportExcel(response, userList, "教师数据");
    }

    /**
     * 导入教师
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "导入教师", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:teacher:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<TeacherExcelVo> util = new ExcelUtil<>(TeacherExcelVo.class);
        List<TeacherExcelVo> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = teacherService.importTeacher(userList, updateSupport, operName);
        return success(message);
    }
}
